package com.example.weight.householdWaste;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.example.weight.R;
import com.example.weight.config.Config;
import com.example.weight.util.Utility;
import com.example.weight.util.WeightActivity;
import com.hjq.bar.OnTitleBarListener;
import com.hjq.bar.TitleBar;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

public class YijingStationResourceActivity extends AppCompatActivity {

    private String name, garbageType, factory;

    private EditText resourceWeight, comment;

    private RadioButton plastic, bag, lunchBox, paper, metalBox, glassBottle, plasticBottle;

    private TextView dailyRecordL, dailyRecordR;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_yijing_station_resource);

        Intent previousIntent = getIntent();
        name = previousIntent.getStringExtra("name");
        factory = previousIntent.getStringExtra("factory");

        TitleBar titleBar = findViewById(R.id.yijing_station_resource_titleBar);
        titleBar.setOnTitleBarListener(new OnTitleBarListener() {
            @Override
            public void onLeftClick(View v) {
                finish();
            }

            @Override
            public void onTitleClick(View v) {}

            @Override
            public void onRightClick(View v) {}
        });

        resourceWeight = findViewById(R.id.yijing_weight);
        plastic = findViewById(R.id.yijing_plastic);
        bag = findViewById(R.id.yijing_plastic_bag);
        lunchBox = findViewById(R.id.yijing_lunch_box);
        paper = findViewById(R.id.yijing_paper);
        metalBox = findViewById(R.id.yijing_metal_box);
        glassBottle = findViewById(R.id.yijing_glass_bottle);
        plasticBottle = findViewById(R.id.yijing_plastic_bottle);
        comment = findViewById(R.id.yijing_comment);
        dailyRecordL = findViewById(R.id.yijing_daily_record_left);
        dailyRecordR = findViewById(R.id.yijing_daily_record_right);

        RequestQueue queue = Volley.newRequestQueue(this);
        String url = Config.url + "/shlj/yijingStationSelling/getamount_day" + "?factory=" + factory;
        StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        try {
                            JSONObject jsonObject = new JSONObject(response);
                            if (!jsonObject.isNull("data")) {
                                JSONArray data = jsonObject.getJSONArray("data");
                                String[] leftArray = dailyRecordL.getText().toString().split("\n");
                                String[] rightArray = dailyRecordR.getText().toString().split("\n");
                                String temp = "";
                                for (int i = 0; i < leftArray.length; i++) {
                                    leftArray[i] = leftArray[i].replace("0", data.getString(i * 2));
                                    temp = temp.concat(leftArray[i]);
                                    if (i != leftArray.length - 1)
                                        temp += "\n";
                                }
                                dailyRecordL.setText(temp);
                                temp = "";
                                for (int i = 0; i < rightArray.length; i++) {
                                    rightArray[i] = rightArray[i].replace("0", data.getString(i * 2 + 1));
                                    temp = temp.concat(rightArray[i]);
                                    if (i != rightArray.length - 1)
                                        temp += "\n";
                                }
                                dailyRecordR.setText(temp);
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(YijingStationResourceActivity.this,
                        "获取信息失败 " + error.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
        stringRequest.setRetryPolicy(new DefaultRetryPolicy(10 * 1000,
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        queue.add(stringRequest);

        plastic.setOnClickListener(v -> {
            bag.setChecked(false);
            lunchBox.setChecked(false);
            paper.setChecked(false);
            metalBox.setChecked(false);
            glassBottle.setChecked(false);
            plasticBottle.setChecked(false);
            garbageType = plastic.getText().toString();
        });
        bag.setOnClickListener(v -> {
            plastic.setChecked(false);
            lunchBox.setChecked(false);
            paper.setChecked(false);
            metalBox.setChecked(false);
            glassBottle.setChecked(false);
            plasticBottle.setChecked(false);
            garbageType = bag.getText().toString();
        });
        lunchBox.setOnClickListener(v -> {
            plastic.setChecked(false);
            bag.setChecked(false);
            paper.setChecked(false);
            metalBox.setChecked(false);
            glassBottle.setChecked(false);
            plasticBottle.setChecked(false);
            garbageType = lunchBox.getText().toString();
        });
        paper.setOnClickListener(v -> {
            plastic.setChecked(false);
            bag.setChecked(false);
            lunchBox.setChecked(false);
            metalBox.setChecked(false);
            glassBottle.setChecked(false);
            plasticBottle.setChecked(false);
            garbageType = paper.getText().toString();
        });
        metalBox.setOnClickListener(v -> {
            plastic.setChecked(false);
            bag.setChecked(false);
            lunchBox.setChecked(false);
            paper.setChecked(false);
            glassBottle.setChecked(false);
            plasticBottle.setChecked(false);
            garbageType = metalBox.getText().toString();
        });
        glassBottle.setOnClickListener(v -> {
            plastic.setChecked(false);
            bag.setChecked(false);
            lunchBox.setChecked(false);
            paper.setChecked(false);
            metalBox.setChecked(false);
            plasticBottle.setChecked(false);
            garbageType = glassBottle.getText().toString();
        });
        plasticBottle.setOnClickListener(v -> {
            plastic.setChecked(false);
            bag.setChecked(false);
            lunchBox.setChecked(false);
            paper.setChecked(false);
            metalBox.setChecked(false);
            glassBottle.setChecked(false);
            garbageType = plasticBottle.getText().toString();
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data != null) {
            String weight = data.getStringExtra("weight");
            resourceWeight.setText(weight);
        }
    }

    public void goWeight(View view) {
        Intent intent = new Intent(YijingStationResourceActivity.this, WeightActivity.class);
        startActivityForResult(intent, 1);
    }

    public void save(View view) {
        if ((!plastic.isChecked() && !bag.isChecked() && !lunchBox.isChecked() && !paper.isChecked() &&
                !metalBox.isChecked() && !glassBottle.isChecked() && !plasticBottle.isChecked())) {
            Toast.makeText(this, "请选择垃圾种类", Toast.LENGTH_SHORT).show();
            return;
        }
        if (!Utility.isNumeric(resourceWeight.getText().toString())) {
            Toast.makeText(this, "重量请填写数字", Toast.LENGTH_SHORT).show();
            return;
        }
        new AlertDialog.Builder(this)
            .setTitle("确定保存吗？")
            .setCancelable(false)
            .setNegativeButton("取消", ((dialog, which) ->
                    Toast.makeText(this, "取消保存", Toast.LENGTH_SHORT).show()))
            .setPositiveButton("确定", (dialog, which) -> {
                // 提交表单
                RequestQueue queue = Volley.newRequestQueue(this);
                String url = Config.url + "/shlj/yijingStationSelling/add";

                StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
                        new Response.Listener<String>() {
                            @Override
                            public void onResponse(String response) {
                                Log.d("zys", response);
                                try {
                                    JSONObject jsonObject = new JSONObject(response);
                                    String code = jsonObject.getString("code");
//                                    plastic.setChecked(false);
//                                    bag.setChecked(false);
//                                    lunchBox.setChecked(false);
//                                    paper.setChecked(false);
//                                    metalBox.setChecked(false);
//                                    glassBottle.setChecked(false);
//                                    plasticBottle.setChecked(false);
//                                    resourceWeight.setText("");
//                                    comment.setText("");

                                    refresh();
                                    if (code.startsWith("2"))
                                        Toast.makeText(YijingStationResourceActivity.this,
                                                "保存成功", Toast.LENGTH_SHORT).show();
                                    else
                                        Toast.makeText(YijingStationResourceActivity.this,
                                                "保存失败", Toast.LENGTH_SHORT).show();
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                            }
                        }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Toast.makeText(YijingStationResourceActivity.this,
                                "保存失败 " + error.getMessage(), Toast.LENGTH_SHORT).show();
                    }
                }) {
                    @Override
                    protected Map<String, String> getParams() {
                        Map<String, String> map=new HashMap<>();
                        map.put("name", garbageType);
                        map.put("amountstr", resourceWeight.getText().toString());
                        map.put("remarks", comment.getText().toString());
                        map.put("factory", factory);
                        return map;
                    }
                };
                stringRequest.setRetryPolicy(new DefaultRetryPolicy(10 * 1000,
                        DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
                queue.add(stringRequest);
            })
            .show();
    }

    // 刷新activity
    public void refresh() {
        finish();
        Intent intent = new Intent(YijingStationResourceActivity.this,
                YijingStationResourceActivity.class);
        intent.putExtra("name", name);
        intent.putExtra("factory", factory);
        startActivity(intent);
    }
}
